package com.watson.webService.config;


import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.binding.soap.saaj.SAAJInInterceptor;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.w3c.dom.NodeList;

import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPMessage;
import java.util.Objects;


/**
 * // todo
 *
 * @author: llun
 * @date: 2022/2/16 16:10
 * @version: 1.0
 */

@Component
public class WebServiceAuthInterceptor extends AbstractPhaseInterceptor<SoapMessage> {
    private static final Logger logger = LoggerFactory.getLogger(WebServiceAuthInterceptor.class);

    private static final String USER_NAME = "admin"; // 用户名
    private static final String USER_PASSWORD = "123456"; //密码
    /**
     * 创建拦截器
     */
    private final SAAJInInterceptor interceptor = new SAAJInInterceptor();

    public WebServiceAuthInterceptor() {
        super(Phase.PRE_PROTOCOL);
        // 添加拦截器
        super.getAfter().add(SAAJInInterceptor.class.getName());
    }


    @Override
    public void handleMessage(SoapMessage message) throws Fault {
        System.out.println("222222222222222222222222");
        // 获取指定信息
        SOAPMessage soapMessage = message.getContent(SOAPMessage.class);
        // 没有消息
        if (soapMessage == null) {
            // 走默认流程
            this.interceptor.handleMessage(message);
            // 再次获取消息
            soapMessage = message.getContent(SOAPMessage.class);
        }
        // SOAP头信息
        SOAPHeader header = null;
        try {
            header = soapMessage.getSOAPHeader();
        } catch (SOAPException e) {
            e.printStackTrace();
        }
        // 没有头信息
        if (header == null) {
            throw new Fault(new IllegalAccessException("找不到header信息"));
        }
        // 解析XML文档（SOAP是XML结构的）
        NodeList usernameList = header.getElementsByTagName("username");
        NodeList passwordList = header.getElementsByTagName("password");
        if (usernameList.getLength() < 1) {
            throw new Fault(new IllegalAccessException("找不到header信息"));
        }
        if (passwordList.getLength() < 1) {
            throw new Fault(new IllegalAccessException("找不到header信息"));
        }
        // 获取用户名
        String username = usernameList.item(0).getTextContent().trim();
        // 获取密码
        String password = passwordList.item(0).getTextContent().trim();

        if (Objects.equals(USER_NAME, username) && Objects.equals(USER_PASSWORD, password)) {
            logger.info("用户访问成功");
        } else {
            SOAPException soapException = new SOAPException("用户认证失败");
            logger.error("用户认证失败");
            throw new Fault(soapException);
        }
    }
}
